package sample8month;
public class QueueNew implements Runnable{

  protected Object[] data;
  protected int writeIndex;
  protected int readIndex;
  protected int count;  //condition

  public QueueNew(int size) {
    data = new Object[size];
    
    
  }


  public int getLength(){
     return data.length;
  }

  public synchronized void write(Object value) { // called by run method of t thread
     while(count >= data.length) {
      try{
        System.out.println("container is full, data can not be written, please wait!");
        wait();  //---return();
      }catch(InterruptedException e) {}
    }

    //write data
    data[writeIndex++] = value;   
    System.out.println("write data is: " + value);  

    // change condition
    count += 1;

    notify(); 
  }

  public synchronized void read() {  // called by main thread
    while(count <= 0){
      try{
	System.out.println("container is empty, data can not be read, please wait!");
        wait();
      }catch(InterruptedException e) {}
    }

    //read data
    Object value = data[readIndex++];
    System.out.println("read data is: " + value);

     // change condition
    count -= 1;
    //notify();

  }
     
   public void run(){  // called by t thread
       for(int i=0;i<data.length;i++) {      
           write(new Integer(i));        
       }
   }

   public static void main(String[] args) {
 
     QueueNew q= new QueueNew(100);       
     Thread t=new Thread(q);

     t.start();  //start t Thread, call run method

     for(int i=0;i<q.getLength();i++) { 
         q.read();           // main thread      
     }   
  }

}

